package com.ikingtech.datav.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.datav.api.SystemConfigApi;
import com.ikingtech.datav.model.constant.FileConstant;
import com.ikingtech.datav.model.entity.SystemConfigDO;
import com.ikingtech.datav.model.request.SystemConfigDTO;
import com.ikingtech.datav.model.request.SystemConfigSearchDTO;
import com.ikingtech.datav.model.result.SystemConfigVO;
import com.ikingtech.datav.service.SystemConfigService;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;

/**
 * created on 2024-03-22 14:45
 *
 * @author wub
 */

@ApiController(value = "/system-config", name = "系统配置systemConfig", description = "系统配置systemConfig")
@RequiredArgsConstructor
public class SystemConfigController implements SystemConfigApi {

    private final SystemConfigService service;

    @Override
    public R<List<SystemConfigVO>> selectByPage(@RequestBody SystemConfigSearchDTO param) {
        return R.ok(this.service.selectByPage(param));
    }

    @Override
    public R<SystemConfigVO> getInfo(@RequestParam("id") String id) {
        return R.ok(this.service.getInfo(id));
    }

    @Override
    public R<String> add(@RequestBody SystemConfigDTO param) {
        this.service.add(param);
        return R.ok();
    }

    @Override
    public R<String> edit(@RequestBody SystemConfigDTO param) {
        this.service.edit(param);
        return R.ok();
    }

    @Override
    public R<String> delete(@RequestParam("id") String id) {
        this.service.delete(id);
        return R.ok();
    }

    @Override
    public R<String> getFileUrl() {
        List<SystemConfigDO> dataV = this.service.getInfoByType("dataV");
        if(dataV.isEmpty()){
            return R.failed(CharSequenceUtil.EMPTY);
        }
        SystemConfigDO systemConfig = dataV.get(0);
        HashMap<String, Object> map = Tools.Json.toBean(systemConfig.getProperties(), new TypeReference<>() {});
        FileConstant.FILE_CDN_URL = map.getOrDefault("fileUrl", CharSequenceUtil.EMPTY).toString();
        return R.ok(FileConstant.FILE_CDN_URL);
    }

    @Override
    public R<SystemConfigVO> byType(@RequestParam("type") String type) {
        SystemConfigDO systemConfig = this.service.getInfoByType(type).get(0);
        return R.ok(BeanUtil.copyProperties(systemConfig,SystemConfigVO.class));
    }

}
